<?php
$cs = Yii::app()->clientScript;

$script = "
jQuery.duplicate = function(me){
    var parent = jQuery(me).parents('.row').first();
    var duplicated = parent.clone();
    jQuery.each(jQuery('input', duplicated), function(){
        jQuery(this).val('');
    });
    
    jQuery('a[class*=\"_trigger\"]', duplicated).text('Select File');
    jQuery('a[class*=\"_remove\"]', duplicated).remove();
    
    parent.after(duplicated);
    
    var container = jQuery(me).parents('.files').first();
    if (jQuery('.row', container).length > 1) {
        jQuery('.remove', container).show();
    }
    
    return false;
}

jQuery.remove = function(me){
    var container = jQuery(me).parents('.files').first();
    
    jQuery(me).parents('.row').first().remove();
    
    if (jQuery('.row', container).length <= 1) {
        jQuery('.remove', container).hide();
    }
    
    return false;
}
//disable remove all input file
jQuery('.files').each(function(){
    var items = jQuery('.row', this);
    if (items.length <= 1) {
        jQuery('.remove', this).hide();
    }
});
";
$cs->registerScript(__CLASS__.'#Duplicate', $script, CClientScript::POS_READY);

$class = get_class($model);
$script = "
var title = $('#".$class."_title');
title.click(function(){
    title.data('value', title.val());
});

title.blur(function(){
    var text = $(this).val();
    if (text == title.data('value')) return;
    var alias = $('#".$class."_alias').val();
    if (alias.replace(/\s+/, '').length > 0) return false;
    var url = text
            .toLowerCase() // change everything to lowercase
            .replace(/^\\s+|\\s+$/g, '') // trim leading and trailing spaces        
            .replace(/[_|\\s]+/g, '-') // change all spaces and underscores to a hyphen
            .replace(/[^a-z0-9-]+/g, '') // remove all non-alphanumeric characters except the hyphen
            .replace(/[-]+/g, '-') // replace multiple instances of the hyphen with a single instance
            .replace(/^-+|-+$/g, '') // trim leading and trailing hyphens                
            ;
    $('#".$class."_alias').val(url);
});
";
$cs->registerScript('title-to-slug',$script, CClientScript::POS_READY);

$script = "
jQuery.fn.ValidateUrl = function(hasError) {
    var is_valid = true;
    
    var data = jQuery('#page-form').serialize();
    jQuery.ajax({
        type    : 'post',
        url     : '".$this->createUrl('/Cms/admin/page/validateUrl')."',
        data    : data,
        async   : false,
        success : function(res){
            res = eval(res);
            if (jQuery.isArray(res))
            {
                for(var i in res)
                {
                    var row = jQuery('#url-container .url:eq('+i+')');
                    if (jQuery.isArray(res[i]) == false)
                    {
                        var input = row.find('.row input');
                        var errorEl = input.next('.errorMessage');
                        if (errorEl.size() == 0)
                        {
                            errorEl = jQuery('<div></div>').addClass('errorMessage');
                            row.find('.row').append(errorEl);
                        }
                        else
                            errorEl.show();
                        errorEl.text(res[i].url[0])
                        is_valid = false;
                    }
                    else
                        row.find('.errorMessage').hide();
                }
            }
        },
        error   : function(){
            is_valid = false;
        }
    });
    
    return is_valid;
}
";
$cs->registerScript(__CLASS__.'ValidateUrl',$script);

$script = "
jQuery('#Page_type').change(function(){
    if (jQuery(this).val() == 'standard')
    {
        jQuery('.type-standard').removeClass('hidden');
    }
    else
    {
        jQuery('.type-standard').addClass('hidden');
    }
});
jQuery('#Page_type').trigger('change');
";
$cs->registerScript(__CLASS__.'ChangeType',$script);
?>
<style type="text/css">
div.wide form #url-container .errorMessage {margin-left: 0;}
.hidden {display: none;}
</style>

<div class="form wide">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'page-form',
    'enableClientValidation'=>true,
    'clientOptions'=>array(
        'validateOnSubmit'=>true,
        'afterValidate'=>'js:function(form, data, hasError){return jQuery.fn.ValidateUrl(hasError);}',
        'afterValidateAttribute'=>'js:function(form, attribute, data, hasError){return jQuery.fn.ValidateUrl(hasError);}',
    )
)); ?>

    <?php if (! $model->IsNewRecord) echo $form->hiddenField($model, "id") ; ?>
    <?php echo $form->hiddenField($model, "parent_id") ; ?>
    <?php echo $form->hiddenField($model,'site_id'); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'title'); ?>
        <?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'title'); ?>
    </div>

    <div class="row">
		<?php echo $form->labelEx($model,'alias'); ?>
		<?php echo $form->textField($model,'alias',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo $form->error($model,'alias'); ?>
	</div>
    
    <div class="row">
        <?php echo $form->labelEx($model,'type'); ?>
        <?php //echo $form->dropDownList($model,'type',$model->typeOptions, array('disabled'=>$model->isNewRecord ? '' : 'disabled')); ?>
        <?php echo $form->dropDownList($model,'type',$model->typeOptions); ?>
        <?php echo $form->error($model,'type'); ?>
    </div>
    
    <div class="row type-standard hidden">
        <?php echo $form->labelEx($model,'route'); ?>
        <?php echo $form->textField($model,'route',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'route', array(), true, false); ?>
    </div>

    <div class="row type-standard hidden">
        <?php echo $form->labelEx($model,'view'); ?>
        <?php echo $form->textField($model,'view',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'view', array(), true, false); ?>
    </div>
    
    <?php if ($model->id <= 0):?>
    <div class="row">
        <?php echo $form->labelEx($pageRevision,'template_content_id', array('label'=>'Template')); ?>  
        <?php $this->widget('Cms.widgets.TemplateContentDropDownList', array(
            'model'=>$pageRevision,
            'attribute'=>'template_content_id',
            'htmlOptions'=>array('class'=>'template-options', 'prompt'=>'---Select---'),
        ));
        ?>
        <?php echo $form->error($pageRevision, 'template_content_id', array(), true, false); ?>
    </div>
    
    <div class="row">
        <?php echo $form->labelEx($pageRevision, 'css_files'); ?>
    </div>
    
    <div class="files">
    <?php foreach ($pageRevision->css_files as $index => $value):?>
    <div class="row">
        <label>&nbsp;</label>
        <?php $this->widget('Admin.components.FileWidget', array(
            'name'=>CHtml::resolveName($pageRevision, $attribute='css_files').'[]',
            'value'=>$value,
            'root'=>'sites/'.str_replace(DIRECTORY_SEPARATOR,'/',SITE_DIR).'/themes/'.Yii::app()->theme->name.'/styles/',
        )); ?>
        <div class="actions">
            <a href="#" onclick="return jQuery.remove(this)" title="Remove" class="remove">Remove</a>
            <a href="#" onclick="return jQuery.duplicate(this)" title="Add" class="add">Add</a>
        </div>
    </div>
    <?php endforeach;?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($pageRevision, 'js_files'); ?>
    </div>
    
    <div class="files">
    <?php foreach ($pageRevision->js_files as $index => $value):?>
    <div class="row">
        <label>&nbsp;</label>
        <?php $this->widget('Admin.components.FileWidget', array(
            'name'=>CHtml::resolveName($pageRevision, $attribute='js_files').'[]',
            'value'=>$value,
            'root'=>'sites/'.str_replace(DIRECTORY_SEPARATOR,'/',SITE_DIR).'/themes/'.Yii::app()->theme->name.'/scripts/',
        )); ?>
        <div class="actions">
            <a href="#" onclick="return jQuery.remove(this)" title="Remove" class="remove">Remove</a>
            <a href="#" onclick="return jQuery.duplicate(this)" title="Add" class="add">Add</a>
        </div>
    </div>
    <?php endforeach;?>
    </div>
    <?php endif;?>

    <?php if ($model->isNewRecord):?>
    <div class="row">
        <?php echo CHtml::label('Urls', 'urls'); ?>
    </div>
    <div id="url-container" style="padding-left: 210px;">
        <?php $this->renderPartial('_url', array('form'=>$form, 'models'=>$pageUrls));?>
    </div>
    <?php endif;?>
    
    <div class="row">
        <?php echo $form->labelEx($model,'allow_cache'); ?>
        <?php echo $form->checkbox($model, 'allow_cache'); ?>
    </div>
    
    <?php if ($model->isNewRecord == false):?>
	<div class="row">
		<?php echo $form->labelEx($model,'creation_datetime'); ?>
        <?php echo Yii::app()->getDateFormatter()->formatDateTime(strtotime($model->creation_datetime)); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'last_update'); ?>
        <?php echo Yii::app()->getDateFormatter()->formatDateTime(strtotime($model->last_update)); ?>
	</div>
    <?php endif; ?>

	<div class="row buttons">
        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
        <?php if ($model->isNewRecord):?>
		    <?php echo CHtml::submitButton('Save and Edit Content', array('submit'=>Yii::app()->controller->createUrl(''), 'params'=>array('task'=>'edit'))); ?>
        <?php endif;?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->
